/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */
package com.fuyao.cloud.asset.cardupdate.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyao.cloud.asset.card.service.AssetAssetcardService;
import com.fuyao.cloud.asset.cardupdate.mapper.AssetAssetUpdateMapper;
import com.fuyao.cloud.asset.cardupdate.service.AssetAssetUpdateService;
import com.fuyao.cloud.asset.cardupdateinfo.service.AssetAssetupdateInfoService;
import com.fuyao.cloud.asset.entity.AssetAssetUpdate;
import com.fuyao.cloud.asset.entity.AssetAssetupdateInfo;
import com.fuyao.cloud.asset.entity.AssetCard;
import com.fuyao.cloud.asset.util.AnnotationUtils;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.compress.utils.Lists;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 资产信息管理
 *
 * @author liyue
 * @date 2021-11-23 09:26:11
 */
@Service
public class AssetAssetUpdateServiceImpl extends ServiceImpl<AssetAssetUpdateMapper, AssetAssetUpdate> implements AssetAssetUpdateService {

    @Lazy
    @Resource
    private AssetAssetcardService assetAssetCardService;

    @Resource
    private AssetAssetupdateInfoService assetAssetUpdateInfoService;

    @Transactional
    @Override
    public boolean save(AssetCard entity) {
        long countAssetCard = this.count(Wrappers.<AssetAssetUpdate>query().lambda().eq(AssetAssetUpdate::getAssetId, entity.getId()));
        AssetAssetUpdate assetAssetUpdate = new AssetAssetUpdate();
        assetAssetUpdate.setAssetId(entity.getId());
        assetAssetUpdate.setAssetName(entity.getName());
        assetAssetUpdate.setAssetNumber(entity.getNumber());

        if (countAssetCard > 0) {
            AssetCard oldAssetCard = this.assetAssetCardService.getById(entity.getId());
            Map<String, Object> assetCardMap = BeanUtil.beanToMap(entity);
            Map<String, Object> oldAssetCardMap = BeanUtil.beanToMap(oldAssetCard);
            StringBuilder updateMessage = new StringBuilder();

            List<AssetAssetupdateInfo> assetUpdateInfoList = Lists.newArrayList();

            assetCardMap.forEach((key, value) -> {
                String annotationValue = AnnotationUtils.getClassFieldAnnotationValue(AssetCard.class, ApiModelProperty.class, key);
                // 新值为空旧数不为空保存记录,或者两者不相等保存记录。。
                if ((null == value && null != oldAssetCardMap.get(key))) {
                    assetUpdateInfoList.add(getAssetUpdateInfo(updateMessage, oldAssetCardMap.get(key), value, key, annotationValue));
                } else if (!(null == value && null == oldAssetCardMap.get(key))) {
                    // BigDecimal类型特殊处理
                    if (value instanceof BigDecimal) {
                        if (((BigDecimal) value).compareTo((BigDecimal) oldAssetCardMap.get(key)) != 0) {
                            assetUpdateInfoList.add(getAssetUpdateInfo(updateMessage, oldAssetCardMap.get(key), value, key, annotationValue));
                        }
                    } else {
                        if (!value.equals(oldAssetCardMap.get(key))) {
                            assetUpdateInfoList.add(getAssetUpdateInfo(updateMessage, oldAssetCardMap.get(key), value, key, annotationValue));
                        }
                    }
                }
            });
            // 修改描述
            assetAssetUpdate.setDescription(updateMessage.toString());
            boolean save = super.save(assetAssetUpdate);
            // 保存修改字段
            if (save) {
                this.saveUpdateInfo(assetUpdateInfoList, assetAssetUpdate);
            }
        } else {
            assetAssetUpdate.setDescription(" first update info ... ");
            super.save(assetAssetUpdate);
        }
        return Boolean.TRUE;
    }

    private AssetAssetupdateInfo getAssetUpdateInfo(StringBuilder updateMessage, Object oldValue, Object newValue, String key, String annotationValue) {
        updateMessage.append(annotationValue).append(":{")
                .append(oldValue)
                .append("修改为:")
                .append(newValue)
                .append("}");
        return AssetAssetupdateInfo.builder().fieldname(key)
                .fieldnameCn(annotationValue)
                .original(String.valueOf(oldValue))
                .modifyValue(String.valueOf(newValue)).
                build();
    }

    private void saveUpdateInfo(List<AssetAssetupdateInfo> assetUpdateInfoList, AssetAssetUpdate assetAssetUpdate) {
        if (CollUtil.isNotEmpty(assetUpdateInfoList)) {
            for (AssetAssetupdateInfo updateInfo : assetUpdateInfoList) {
                updateInfo.setParentId(assetAssetUpdate.getId());
                updateInfo.setAssetName(assetAssetUpdate.getAssetName());
            }
            this.assetAssetUpdateInfoService.saveBatch(assetUpdateInfoList);
        }
    }

}
